const express = require('express');
const router = express.Router();
const { successResponse, failureResponse } = require('../utils/responses')
const { config, client, singleFileUpload } = require('../utils/aliyun');
const { BadRequestError } = require('../utils/errors');
const moment = require('moment');
const { v4: uuidv4 } = require('uuid')

// 文件上传 - 服务器代理上传
router.post('/aliyun', async (req, res) => {
  try {
    singleFileUpload(req, res, function(err) {
      if (err) {
        return failureResponse(res, err.message);
      }

      if (!req.file) {
        return failureResponse(res, new BadRequestError('请选择要上传的文件'));
      }
      successResponse(res, '文件上传成功', { file: req.file });
    })
  } catch (error) {
    failureResponse(res, error.message);
  }
})

// 文件直传 - 获取阿里云直传授权信息
router.get('/aliyun_direct', async (req, res) => {
  // 有效期
  const date = moment().add(1, 'days')
  // 自定义上传目录及文件名
  const key = `uploads/${uuidv4()}`

  // 安全策略
  const policy = {
    expiration: date.toISOString(), // 限制有效期
    conditions: [
      ['content-length-range', 0, 5 * 1024 * 1024],
      { bucket: client.options.bucket }, // 限制上传的 bucket
      ['eq', '$key', key],
      [ 'in', '$content-type', ['image/jepg', 'image/png', 'image/gif', 'image/webp' ]], // 限制文件类型
    ]
  }

  // 签名
  const formData = client.calculatePostSignature(policy)

  // bucket 域名(阿里云上传地址)
  const host = `https://${config.bucket}.${(await client.getBucketLocation()).location}.aliyuncs.com`.toString()

  const params = {
    expire: date.format('YYYY-MM-DDTHH:mm:ssZ'),
    host,
    key,
    url: host + '/' + key,
    policy: formData.policy,
    signature: formData.Signature,
    accessid: formData.OSSAccessKeyId,
  }
  successResponse(res, '获取阿里云 OSS 授权成功', params)
})

module.exports = router;